package com.letv.android.client.album.controller;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.RelativeLayout;

import com.letv.android.client.activity.AlbumPlayActivity;
import com.letv.android.client.activity.AlbumPlayRoomActivity;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.core.api.LetvRequest;
import com.letv.core.api.MediaAssetApi;
import com.letv.core.bean.DataHull;
import com.letv.core.bean.WaterMarkBean;
import com.letv.core.bean.WaterMarkBean.Imgs;
import com.letv.core.constant.NetworkConstant;
import com.letv.core.constant.PlayConstant;
import com.letv.core.download.image.ImageDownloadStateListener;
import com.letv.core.download.image.ImageDownloader;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyRequest.RequestManner;
import com.letv.core.network.volley.VolleyResponse.CacheResponseState;
import com.letv.core.network.volley.VolleyResponse.NetworkResponseState;
import com.letv.core.network.volley.toolbox.SimpleResponse;
import com.letv.core.network.volley.toolbox.VolleyDiskCache;
import com.letv.core.parser.WaterMarkParser;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.NetworkUtils;
import com.letv.core.utils.UIsUtils;

import java.util.List;

/**
 * 水印工具类
 * 
 * @author zhuqiao
 *
 */
public class AlbumWaterMarkController {
    private static final String WATER_MARK_CACHE_KEY = "waterMark";

    private final Context mContext;
    private final ImageView mWaterMarkImageView;
    private final View mPlayerFrame;
    private MediaPlayerControl mVideoView;

    private boolean mIsAlreadyWaterStart;
    private WaterMarkBean mWaterMark;
    private List<Imgs> mImgList;
    private int mOldOff = 0;
    private int[] mMargins;
    /** 水印使能标志 **/
    private boolean mIsWaterEnable = false;
    private Handler mWaterHandler = new Handler();

    private int mWaterIndex;
    private int mLastTime;
    private int mIndex;
    private Bitmap mLastBitmap;

    /** 是否需要暂停水印 **/
    private boolean mIsNeedPauseWater;

    private Runnable mWaterRunnable;

    public AlbumWaterMarkController(Context context, ImageView waterMarkImageView, View playerFrame) {
        mContext = context;
        mWaterMarkImageView = waterMarkImageView;
        mPlayerFrame = playerFrame;
    }

    /**
     * 设置是否需要暂停水印
     * 
     * @param needPause
     */
    public void setNeedPauseWater(boolean needPause) {
        mIsNeedPauseWater = needPause;
    }

    /**
     * 改变水印方向
     */
    public void changeWaterMarkDirection() {
        try {
            if (mWaterMarkImageView != null) {
                final boolean isShow = mWaterMarkImageView.getVisibility() == View.VISIBLE;
                if (isShow) {
                    mWaterMarkImageView.setVisibility(View.GONE);
                }
                mWaterHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mWaterMark != null && mMargins != null && mWaterMark.getImgses() != null
                                && mWaterMarkImageView != null) {
                            mMargins = getMargin(Integer.parseInt(mWaterMark.getOFFSET()));
                            changeImagePosition(mWaterMark.getImgses().get(mIndex), null, mMargins);

                            if (isShow) {
                                mWaterMarkImageView.setVisibility(View.VISIBLE);
                            }

                        }
                    }
                }, 200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始请求水印
     */
    public boolean startWaterMark(MediaPlayerControl videoView) {
        mVideoView = videoView;
        if (!mVideoView.isPlaying()) {
            return false;
        }

        if (!mIsAlreadyWaterStart) {
            // 延迟两秒播放器初始化加载
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    requestWaterMark();
                }
            }, 2000);
            mIsAlreadyWaterStart = true;
            return true;
        } else {
            if (mWaterMarkImageView != null && mWaterMarkImageView.getVisibility() != View.VISIBLE) {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mWaterMarkImageView.setVisibility(View.VISIBLE);
                    }
                }, 2000);
                return true;
            }
        }

        return false;
    }

    /**
     * 请求水印
     */
    private void requestWaterMark() {
        if(mContext instanceof AlbumPlayActivity) {
            if (((AlbumPlayActivity) mContext).getFlow() == null)
                return;

            if (mVideoView == null || mWaterMarkImageView == null) {
                return;
            }

            AlbumPlayFlow flow = ((AlbumPlayActivity) mContext).getFlow();

            if (flow.getLaunchMode() == PlayConstant.PLAY_DEFAULT) {
                return;
            }

            if (UIsUtils.getScreenWidth(mContext) <= 200)
                return;

            if (mWaterRunnable != null) {
                mWaterHandler.removeCallbacks(mWaterRunnable);
            }
        } else if(mContext instanceof AlbumPlayRoomActivity) {
            if (((AlbumPlayRoomActivity) mContext).getFlow() == null)
                return;

            if (mVideoView == null || mWaterMarkImageView == null) {
                return;
            }

            AlbumPlayFlow flow = ((AlbumPlayRoomActivity) mContext).getFlow();

            if (flow.getLaunchMode() == PlayConstant.PLAY_DEFAULT) {
                return;
            }

            if (UIsUtils.getScreenWidth(mContext) <= 200)
                return;

            if (mWaterRunnable != null) {
                mWaterHandler.removeCallbacks(mWaterRunnable);
            }
        } else {
            return;
        }

        // wifi情况下,每回都去服务器获取信息
        if (NetworkUtils.getNetworkType(mContext) == NetworkConstant.NETWORK_TYPE_WIFI) {
            requestWaterMarkFromNetwork(true);
        } else {
            requestWaterMarkFromCache(true);
        }
    }

    /**
     * 从网络获取水印信息
     * 
     * @param fetchCacheWhenError 当请求错误,是否再上缓存获取数据
     */
    private void requestWaterMarkFromNetwork(final boolean fetchCacheWhenError) {
        if(mContext instanceof AlbumPlayActivity) {
            if (((AlbumPlayActivity) mContext).getFlow() == null)
                return;

            AlbumPlayFlow flow = ((AlbumPlayActivity) mContext).getFlow();

            new LetvRequest<WaterMarkBean>(mContext)
                    .setUrl(MediaAssetApi.getInstance().getWaterMarkUrl(mContext,(int) flow.getCid(), flow.getAid()))
                    .setCache(new VolleyDiskCache(mContext, WATER_MARK_CACHE_KEY + flow.getCid()))
                    .setParser(new WaterMarkParser()).setRequestType(RequestManner.NETWORK_ONLY)
                    .setCallback(new SimpleResponse<WaterMarkBean>() {

                        @Override
                        public void onNetworkResponse(VolleyRequest<WaterMarkBean> request, WaterMarkBean result,
                                                      DataHull hull, NetworkResponseState state) {
                            if (state == NetworkResponseState.SUCCESS) {
                                displayWaterMark(result);
                            } else if (fetchCacheWhenError) {
                                requestWaterMarkFromCache(false);
                            }
                        }

                    }).add();
        } else if(mContext instanceof AlbumPlayRoomActivity) {
            if (((AlbumPlayRoomActivity) mContext).getFlow() == null)
                return;

            AlbumPlayFlow flow = ((AlbumPlayRoomActivity) mContext).getFlow();

            new LetvRequest<WaterMarkBean>(mContext)
                    .setUrl(MediaAssetApi.getInstance().getWaterMarkUrl(mContext,(int) flow.getCid(), flow.getAid()))
                    .setCache(new VolleyDiskCache(mContext, WATER_MARK_CACHE_KEY + flow.getCid()))
                    .setParser(new WaterMarkParser()).setRequestType(RequestManner.NETWORK_ONLY)
                    .setCallback(new SimpleResponse<WaterMarkBean>() {

                        @Override
                        public void onNetworkResponse(VolleyRequest<WaterMarkBean> request, WaterMarkBean result,
                                                      DataHull hull, NetworkResponseState state) {
                            if (state == NetworkResponseState.SUCCESS) {
                                displayWaterMark(result);
                            } else if (fetchCacheWhenError) {
                                requestWaterMarkFromCache(false);
                            }
                        }

                    }).add();
        }

    }

    /**
     * 从缓存中获取水印信息
     * 
     * @param fetchNetworkWhenError 当缓存出错，是否再上服务器上获取数据
     */
    private void requestWaterMarkFromCache(final boolean fetchNetworkWhenError) {
        if(mContext instanceof AlbumPlayActivity) {
            if (((AlbumPlayActivity) mContext).getFlow() == null)
                return;

            AlbumPlayFlow flow = ((AlbumPlayActivity) mContext).getFlow();

            new LetvRequest<WaterMarkBean>(mContext)
                    .setUrl(MediaAssetApi.getInstance().getWaterMarkUrl(mContext,(int) flow.getCid(), flow.getAid()))
                    .setCache(new VolleyDiskCache(mContext, WATER_MARK_CACHE_KEY + flow.getCid()))
                    .setParser(new WaterMarkParser()).setRequestType(RequestManner.CACHE_ONLY)
                    .setCallback(new SimpleResponse<WaterMarkBean>() {

                        @Override
                        public void onCacheResponse(VolleyRequest<WaterMarkBean> request, WaterMarkBean result,
                                                    DataHull hull, CacheResponseState state) {
                            if (state == CacheResponseState.SUCCESS) {
                                displayWaterMark(result);
                            } else if (fetchNetworkWhenError) {
                                requestWaterMarkFromNetwork(false);
                            }
                        }

                    }).add();
        } else if(mContext instanceof AlbumPlayRoomActivity) {
            if (((AlbumPlayRoomActivity) mContext).getFlow() == null)
                return;

            AlbumPlayFlow flow = ((AlbumPlayRoomActivity) mContext).getFlow();

            new LetvRequest<WaterMarkBean>(mContext)
                    .setUrl(MediaAssetApi.getInstance().getWaterMarkUrl(mContext,(int) flow.getCid(), flow.getAid()))
                    .setCache(new VolleyDiskCache(mContext, WATER_MARK_CACHE_KEY + flow.getCid()))
                    .setParser(new WaterMarkParser()).setRequestType(RequestManner.CACHE_ONLY)
                    .setCallback(new SimpleResponse<WaterMarkBean>() {

                        @Override
                        public void onCacheResponse(VolleyRequest<WaterMarkBean> request, WaterMarkBean result,
                                                    DataHull hull, CacheResponseState state) {
                            if (state == CacheResponseState.SUCCESS) {
                                displayWaterMark(result);
                            } else if (fetchNetworkWhenError) {
                                requestWaterMarkFromNetwork(false);
                            }
                        }

                    }).add();
        }

    }

    private void displayWaterMark(WaterMarkBean waterMark) {
        // 防止出现播放器还没初始化
        if (!mVideoView.isPlaying() || waterMark == null)
            return;

        display(waterMark);
    }

    /**
     * 显示水印
     * 
     * @param waterMark
     */
    private void display(WaterMarkBean waterMark) {
        if (waterMark == null || BaseTypeUtils.isListEmpty(waterMark.getImgses())) {
            return;
        }

        mWaterMark = waterMark;
        mImgList = waterMark.getImgses();
        mMargins = getMargin(BaseTypeUtils.stoi(waterMark.getOFFSET()));
        mIsWaterEnable = true;

        mWaterRunnable = getWaterRunnable();
        mWaterRunnable.run();
    }

    private int[] getMargin(int per) {
        if (per == 0) {
            per = mOldOff;
        }

        int[] margins = new int[2];
        margins[0] = mPlayerFrame.getWidth() * per / 100;
        margins[1] = mPlayerFrame.getHeight() * per / 100;
        mOldOff = per;
        return margins;
    }

    private Runnable getWaterRunnable() {
        if (mImgList.size() == mWaterIndex) {
            mWaterIndex = 0;
        }
        mLastTime = Integer.parseInt(mImgList.get(mWaterIndex).getLASTTIME()) * 1000;

        Runnable run = new Runnable() {

            @Override
            public void run() {
                mWaterHandler.removeCallbacks(this);
                if (mMargins == null || mLastTime == 0 || !mIsWaterEnable) {
                    return;
                }

                if (mIsNeedPauseWater) {
                    mWaterIndex--;
                    if (mWaterIndex < 0) {
                        mWaterIndex = mImgList.size() - 1;
                    }
                }

                mIndex = mWaterIndex;
                displayPic(mImgList.get(mWaterIndex), mMargins);
                mWaterIndex++;
                mMargins = getMargin(BaseTypeUtils.stoi(mWaterMark.getOFFSET()));

                mWaterRunnable = getWaterRunnable();
                mWaterHandler.postDelayed(mWaterRunnable, mLastTime);
            }

        };

        return run;
    }

    /**
     * 显示图片
     * 
     * @param img
     * @param margins
     */
    private void displayPic(final Imgs img, final int[] margins) {
        if (img == null) {
            return;
        }

        ImageDownloader.getInstance(mContext).download(img.getURL100(), new ImageDownloadStateListener() {

            @Override
            public void loading() {
            }

            @Override
            public void loadSuccess(Bitmap bitmap) {
                mWaterMarkImageView.setImageBitmap(bitmap);
                if (mVideoView.isPlaying()) {
                    mWaterMarkImageView.setVisibility(View.VISIBLE);
                    changeImagePosition(img, bitmap, margins);
                }

            }

            @Override
            public void loadFailed() {
            }
        });
    }

    private void changeImagePosition(final Imgs img, Bitmap loadedImage, final int[] mars) {
        if (TextUtils.isEmpty(img.getURL100())) {
            return;
        }
        if (loadedImage != null) {
            mLastBitmap = loadedImage;
        } else {
            loadedImage = mLastBitmap;
        }

        if (mWaterMarkImageView != null && loadedImage != null) {
            int index = Integer.parseInt(img.getPOSITION());
            RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) mWaterMarkImageView.getLayoutParams();
            param.width = (param.height * loadedImage.getWidth()) / loadedImage.getHeight();
            setWaterMarkMars(index, param, mars);
            mWaterMarkImageView.setLayoutParams(param);
        }
    }

    private void setWaterMarkMars(int index, RelativeLayout.LayoutParams param, final int[] mars) {
        switch (index) {
            case 1:
                param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                param.setMargins(mars[0], mars[1], 0, 0);
                break;
            case 2:
                param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                param.setMargins(0, mars[1], mars[0], 0);
                break;
            case 3:
                param.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                param.setMargins(mars[0], 0, 0, mars[1]);
                break;
            case 4:
                param.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
                param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                param.setMargins(0, 0, mars[0], mars[1]);
                break;
            default:
                break;
        }
    }
}
